package common.struct;

import com.alibaba.fastjson.JSONObject;
import common.struct.ConstantEnum.ServiceType;

public class ServiceInfo {
    public ServiceType type;
    public String appName;
    public State state;
    public ServiceConfig config;
    public ServiceResult result;
    public JSONObject jo;

    public ServiceInfo(ServiceType type, String appName, State state, ServiceConfig config, ServiceResult result) {
        this.type = type;
        this.appName = appName;
        this.state = state;
        this.config = config;
        this.result = result;
    }

    public ServiceInfo(JSONObject obj) {
        this.jo = obj;
        this.type = ServiceType.fromString(obj.getString("service_type"));
        this.appName = obj.getString("app_name");
        this.state = State.fromString(obj.getString("state"));
        if (type == ServiceType.CTX) {
            try {
                this.config = CtxServiceConfig.fromJSONString(obj.getString("config"));
            } catch (Exception ignored) {}
            try {
                this.result = CtxServiceResult.fromJSONString(obj.getString("result"));
            } catch (Exception ignored) {}
        } else {
            try {
                this.config = InvServiceConfig.fromJSONString(obj.getString("config"));
            } catch (Exception ignored) {}
            try {
                this.result = InvServiceResult.fromJSONString(obj.getString("result"));
            } catch (Exception ignored) {}
        }
    }

    @Override
    public String toString() {
        if (jo != null) return jo.toJSONString();
        jo = new JSONObject();
        jo.put("service_type", type.toString());
        jo.put("app_name", appName);
        jo.put("state", state.toString());
        jo.put("config", config == null ? null : config.toJSONObject());
        jo.put("result", result == null ? null : result.toJSONObject());
        return jo.toJSONString();
    }

    public JSONObject toJSONObject() {
        if (jo != null) return jo;
        jo = new JSONObject();
        jo.put("service_type", type.toString());
        jo.put("app_name", appName);
        jo.put("state", state.toString());
        jo.put("config", config == null ? null : config.toJSONObject());
        jo.put("result", result == null ? null : result.toJSONObject());
        return jo;
    }
}
